package com.dxg.msns.auth.controller;

import com.dxg.msns.auth.entity.UserInfo;
import com.dxg.msns.auth.properties.JwtProperties;
import com.dxg.msns.auth.service.AuthService;
import com.dxg.msns.auth.utils.CookieUtils;
import com.dxg.msns.auth.utils.JwtUtils;
import com.dxg.msns.common.util.Result;
import com.dxg.msns.user.pojo.User;
import com.dxg.msns.user.pojo.UserLoginVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/")
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {
    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录 - 返回UserLoginVO对象
     * 适用于Authorization请求头的认证方式
     * 
     * @param uname     用户名
     * @param upassword 密码
     * @return 统一响应格式，data字段包含UserLoginVO对象
     */
    @PostMapping("/login")
    public ResponseEntity<Result<UserLoginVO>> login(@RequestParam("uname") String uname,
            @RequestParam("upassword") String upassword) {
        try {
            // 参数验证
            if (StringUtils.isEmpty(uname) || StringUtils.isEmpty(upassword)) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Result.error("用户名和密码不能为空"));
            }

            // 登录校验，获取用户信息和token
            UserLoginVO loginVO = this.authService.loginAndGetUserInfo(uname, upassword);
            if (loginVO == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                        .body(Result.error("用户名或密码错误"));
            }

            // 返回成功结果，data字段包含UserLoginVO对象
            return ResponseEntity.ok(Result.success("登录成功",loginVO));

        } catch (Exception e) {
            System.err.println("登录异常：" + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Result.error("登录失败：" + e.getMessage()));
        }
    }

    /**
     * 用户登录 - Cookie方式（向后兼容）
     * 
     * @param uname     用户名
     * @param upassword 密码
     * @param request   请求
     * @param response  响应
     * @return 响应结果
     */
    @PostMapping("/accredit")
    public ResponseEntity<Void> authentication(@RequestParam("uname") String uname,
            @RequestParam("upassword") String upassword,
            HttpServletRequest request,
            HttpServletResponse response) {
        // 登录校验，生成token
        String token = this.authService.authentication(uname, upassword);
        if (StringUtils.isEmpty(token)) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        // 将token写入cookie，并指定httpOnly为true，防止js获取修改
        CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), token,
                this.jwtProperties.getCookieMaxAge(), null, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除cookie
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/deleteCookie")
    public ResponseEntity<Void> deleteCookie(HttpServletRequest request, HttpServletResponse response) {
        CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), null, 0, null, true);
        return ResponseEntity.ok().build();
    }

    /**
     * 验证用户Token - 支持Authorization请求头
     * 
     * @param request 请求
     * @return 用户信息
     */
    @GetMapping("/verify")
    public ResponseEntity<UserInfo> verifyUser(HttpServletRequest request) {
        try {
            // 优先从Authorization请求头获取token
            String token = getTokenFromRequest(request);
            if (StringUtils.isEmpty(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 从token中解析信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            User user = authService.getUser(userInfo);
            userInfo.setAvatarUrl(user.getAvatarUrl());
            userInfo.setId(user.getId());
            userInfo.setUid(user.getUid());
            userInfo.setUname(user.getUname());

            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }

    /**
     * 获取用户信息 - 支持Authorization请求头
     * 
     * @param request 请求
     * @return 用户信息
     */
    @GetMapping("/getUser")
    public ResponseEntity<User> getUser(HttpServletRequest request) {
        try {
            // 优先从Authorization请求头获取token
            String token = getTokenFromRequest(request);
            if (StringUtils.isEmpty(token)) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }

            // 从token中解析信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            User user = authService.getUser(userInfo);

            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
    }

    @GetMapping("/changePwd")
    public ResponseEntity<Void> changeUserPwd(@CookieValue("MSNS_TOKEN") String token,
            @RequestParam("upassword") String upassword,
            @RequestParam("newPassword") String newPassword,
            HttpServletRequest request,
            HttpServletResponse response) {
        // System.out.println("token:::"+token);
        try {
            // 从token'中解析信息
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, this.jwtProperties.getPublicKey());
            authService.changePwd(upassword, newPassword, userInfo.getId());
            // 解析成功要重新刷新token
            token = JwtUtils.generateToken(userInfo, this.jwtProperties.getPrivateKey(),
                    this.jwtProperties.getExpire());
            // 更新cookie中的token
            CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), token,
                    this.jwtProperties.getCookieMaxAge(), null, true);
            // 解析成功返回用户信息
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 从请求中获取Token
     * 优先级：Authorization请求头 > Cookie
     * 
     * @param request HTTP请求
     * @return JWT Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 优先从Authorization请求头获取
        String authHeader = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(authHeader) && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7); // 去除"Bearer "前缀
        }

        // 备用方案：从Cookie获取
        String cookieValue = null;
        if (request.getCookies() != null) {
            for (javax.servlet.http.Cookie cookie : request.getCookies()) {
                if (jwtProperties.getCookieName().equals(cookie.getName())) {
                    cookieValue = cookie.getValue();
                    break;
                }
            }
        }

        return cookieValue;
    }
}
